// websocket-adapters.js - 平台适配器
import { WebSocketCore } from './websocket-core.js'
/**
 * UniApp环境WebSocket适配器
 */
export class UniAppWebSocketAdapter extends WebSocketCore {
  _connect() {
    // 关闭现有连接
    if (this.socketTask) {
      this._closeRaw()
    }
    
    console.log('[WebSocket] (UniApp) Connecting to', this.url)
    
    this.socketTask = uni.connectSocket({
      url: this.url,
      complete: () => {}
    })
    
    // 绑定事件
    this.socketTask.onOpen(() => {
      this._handlePlatformOpen()
    })
    
    this.socketTask.onMessage((res) => {
      this._handlePlatformMessage(res.data)
    })
    
    this.socketTask.onError((err) => {
      this._handlePlatformError(err)
    })
    
    this.socketTask.onClose((res) => {
      this._handlePlatformClose(res)
    })
  }
  
  _sendRaw(message) {
    if (!this.socketTask) return
    
    this.socketTask.send({
      data: message,
      success: () => {},
      fail: (err) => {
        console.error('[WebSocket] (UniApp) Send error:', err)
        this.messageQueue.push(message) // 发送失败重新入队
      }
    })
  }
  
  _closeRaw(code) {
    if (!this.socketTask) return
    
    this.socketTask.close({
      code: code,
      complete: () => {
        this.socketTask = null
      }
    })
  }
}

/**
 * Web环境WebSocket适配器
 */
export class WebWebSocketAdapter extends WebSocketCore {
  _connect() {
    // 关闭现有连接
    if (this.socket) {
      this._closeRaw()
    }
    
    console.log('[WebSocket] (Web) Connecting to', this.url)
    
    this.socket = new WebSocket(this.url)
    
    // 绑定事件
    this.socket.onopen = () => {
      this._handlePlatformOpen()
    }
    
    this.socket.onmessage = (event) => {
      this._handlePlatformMessage(event.data)
    }
    
    this.socket.onerror = (error) => {
      this._handlePlatformError(error)
    }
    
    this.socket.onclose = (event) => {
      this._handlePlatformClose(event)
    }
  }
  
  _sendRaw(message) {
    if (!this.socket) return
    
    try {
      this.socket.send(message)
    } catch (e) {
      console.error('[WebSocket] (Web) Send error:', e)
      this.messageQueue.push(message)
    }
  }
  
  _closeRaw(code) {
    if (!this.socket) return
    
    this.socket.close(code || 1000)
    this.socket = null
  }
}